/*
 * @Author: wangtao
 * @Date: 2020-08-20 14:07:42
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-07-14 13:47:21
 * @Description:
 */

import React from 'react';
import {
  View,
  StyleSheet,
  SafeAreaView,
  ScrollView,
  NativeModules,
} from 'react-native';
import api from '@/api';
import {} from '@/images';
import { msg, Button } from '@/common';
import {
  isAndroid,
  mainBgColorLightGray,
  fontColorCoffee,
  px2dp,
} from '@/styles';
import { uploadImage } from '@/config';

import FaceCer from './components/face-cer';
import DriverLicense from './components/driver-license';
import WorkLicense from './components/work-license';
import ChooseAgreement from './components/choose-agreement';

const { Submit } = Button;

export default class DriverCer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      faceImgId: '', //  人脸照片   不能为空
      driverLicencePhotoFrontId: '', // 驾驶证正面   不能为空
      driverLicencePhotoBackId: '', //  驾驶证背面    不能为空
      frontPhotoId: '', //  驾驶证副页正面
      backPhotoId: '', //  驾驶证副页背面
      qualificationPhotoFrontId: '', //  从业资格证正面  不能为空
      qualificationPhotoBackId: '', //  从业资格证背面   不能为空
      proveImgId: '', //  三年无事故证明照片   不能为空
      isAgree: true, // 是否同意协议
    };
  }

  // onChange
  onChange = (type, val) => {
    // 个别ocr识别
    this.ocr(type, val);
    this.setState({ [type]: val });
  };

  render() {
    const {
      faceImgId,
      driverLicencePhotoFrontId,
      driverLicencePhotoBackId,
      frontPhotoId,
      backPhotoId,
      qualificationPhotoFrontId,
      qualificationPhotoBackId,
      isAgree,
    } = this.state;
    return (
      <SafeAreaView style={{ flex: 1 }}>
        <View style={styles.container}>
          <ScrollView
            contentContainerStyle={{ paddingBottom: 100, alignItems: 'center' }}
            showsVerticalScrollIndicator={false}
          >
            {/* 人脸识别 */}
            <FaceCer selectImg={this._selectImg} faceImgId={faceImgId} />
            {/* 驾驶证 */}
            <DriverLicense
              selectImg={this._selectImg}
              driverLicencePhotoFrontId={driverLicencePhotoFrontId}
              driverLicencePhotoBackId={driverLicencePhotoBackId}
              frontPhotoId={frontPhotoId}
              backPhotoId={backPhotoId}
            />
            {/* 从业资格证 */}
            <WorkLicense
              selectImg={this._selectImg}
              qualificationPhotoFrontId={qualificationPhotoFrontId}
              qualificationPhotoBackId={qualificationPhotoBackId}
            />
            {/* 三年无事故证明 */}
            {/* <ThingsLicense selectImg={this._selectImg} proveImgId={proveImgId} /> */}
            {/* 《货物运输协议》 */}
            <ChooseAgreement
              isAgree={isAgree}
              onChange={(type, val) => this.onChange(type, val)}
            />
            <Submit
              text='提交'
              onClick={() => {
                this.submitCer();
              }}
              boxStyle={{
                width: px2dp(640),
                height: px2dp(96),
                borderRadius: px2dp(46),
                borderWidth: 1,
                borderColor: fontColorCoffee,
                marginTop: px2dp(64),
              }}
              btnTextStyle={{
                fontSize: px2dp(36),
              }}
            />
          </ScrollView>
        </View>
      </SafeAreaView>
    );
  }

  // 选择照片
  _selectImg = (type) => {
    if (type === 'faceImgId' && isAndroid) {
      NativeModules.DataModule.chooseFaceImage((path, imageBase64) => {
        this.upload(path, type);
      });
    } else {
      NativeModules.DataModule.chooseImage((path, imageBase64) => {
        this.upload(path, type);
      });
    }
  };

  // 上传照片
  upload(path, type) {
    NativeModules.WindowModule.showLoading();
    uploadImage('upload?dirName=driverCer', path)
      .then((res) => {
        console.log('🚀🚀🚀wimi======>>>res', res);
        // 请求成功
        if (res.success) {
          this.onChange(type, res.data.localId);
        } else {
          NativeModules.WindowModule.showWindow(
            { content: '上传失败，请重试', onlyRightBtn: '1' },
            (e) => {},
          );
        }
        NativeModules.WindowModule.dismissLoading();
      })
      .catch((err) => {
        NativeModules.WindowModule.dismissLoading();
        // 请求失败
        NativeModules.WindowModule.showWindow(
          { content: '上传出错，请重试', onlyRightBtn: '1' },
          (e) => {},
        );
      });
  }

  // ocr
  ocr = (type, val) => {
    if (type === 'driverLicencePhotoFrontId') {
      api.supply.driverLicenseOcr(val).then((res) => {
        if (res.success) {
          console.log('🚀🚀🚀wimi======>>>111');
        } else {
          this.setState({ driverLicencePhotoFrontId: '' });
          msg.emit('app:tip', { text: '请重新上传驾驶证主页正面' });
        }
      });
    } else if (type === 'qualificationPhotoFrontId') {
      api.supply.roadQuaOcr(val).then((res) => {
        if (res.success) {
          console.log('🚀🚀🚀wimi======>>>111');
        } else {
          this.setState({ qualificationPhotoFrontId: '' });
          msg.emit('app:tip', { text: '请重新上传从业资格证正面' });
        }
      });
    }
  };

  // 司机认证
  submitCer = () => {
    const {
      faceImgId,
      driverLicencePhotoFrontId,
      driverLicencePhotoBackId,
      frontPhotoId,
      backPhotoId,
      qualificationPhotoFrontId,
      qualificationPhotoBackId,
      // proveImgId,
      isAgree,
    } = this.state;
    const params = {
      faceImgId,
      driverLicencePhotoFrontId,
      driverLicencePhotoBackId,
      frontPhotoId,
      backPhotoId,
      qualificationPhotoFrontId,
      qualificationPhotoBackId,
      // proveImgId,
    };

    if (!faceImgId) {
      msg.emit('app:tip', { text: '请进行人脸识别' });
      return;
    }
    if (!driverLicencePhotoFrontId) {
      msg.emit('app:tip', { text: '请上传驾驶证正面' });
      return;
    }
    if (!driverLicencePhotoBackId) {
      msg.emit('app:tip', { text: '请上传驾驶证背面' });
      return;
    }
    if (!frontPhotoId) {
      msg.emit('app:tip', { text: '请上传驾驶证副页正面' });
      return;
    }
    if (!backPhotoId) {
      msg.emit('app:tip', { text: '请上传驾驶证副页背面' });
      return;
    }
    if (!qualificationPhotoFrontId) {
      msg.emit('app:tip', { text: '请上传从业资格证正面' });
      return;
    }
    if (!qualificationPhotoBackId) {
      msg.emit('app:tip', { text: '请上传从业资格证背面' });
      return;
    }
    // if (!proveImgId) {
    //   msg.emit('app:tip', {text: '请上传三年无事故证明'});
    //   return;
    // }
    if (!isAgree) {
      msg.emit('app:tip', { text: '请同意货运运输协议' });
      return;
    }

    api.supply.driverCer(params).then((res) => {
      if (res.success) {
        this.getDriverCer();
      } else {
        msg.emit('app:tip', { text: '请重新上传' });
      }
    });
  };

  // 获取司机认证状态
  getDriverCer = () => {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { routerFrom } = params;
    api.supply.getDriverCer().then((res) => {
      if (res.success) {
        if (res.data.state === 1) {
          msg.emit('router: goToNext', {
            routeName: 'FeedBackDriverCer',
            status: 1,
            title: '司机认证已提交审核中',
            desc: '工作人员将在3个工作日内给予答复',
            routerFrom,
          });
        }
        if (res.data.state === 2) {
          msg.emit('router: goToNext', {
            routeName: 'FeedBackDriverCer',
            status: 0,
            title: '非常抱歉，您未能通过认证',
            desc: res.data.descrption,
            routerFrom,
            routerTo: 'DriverCer',
          });
        }
      }
    });
  };
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
  },
});
